//
//  LRHomeViewController.m
//  本地生活圈
//
//  Created by admin on 15/8/10.
//  Copyright (c) 2015年 懒人. All rights reserved.
//

#import "LRHomeViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "LRHomeModel.h"
#import "LRLocationManager.h"
#import "LRHomeHeardCell.h"
#import "LRFamousTableViewCell.h"
#import "LRGroupTableViewCell.h"
#import "LRGuessTableViewCell.h"
#import "LRDetailFamousViewController.h"

@interface LRHomeViewController ()<CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate,LRFamousListDelegate>
/**
 *  网络访问
 */
//@property (nonatomic, strong) AFHTTPRequestOperationManager *manager;
/**
 *  模型数据
 */
@property (nonatomic, strong) LRHomeModel *homeModel;

/**
 *  定位
 */
@property (nonatomic, assign) CLLocationCoordinate2D location;

/**
 *  表头
 */
@property (nonatomic, strong) LRHomeHeardCell *header;

/**
 *  tableview
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *  刷新
 */
@property (nonatomic, strong) UIRefreshControl *refresh;
@end

@implementation LRHomeViewController

#pragma mark - Getter/Settet

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, kUIScreenW, kUIScreenH - kNavHeight - kTabBarHeight)]; // 或者修改tabbar的设置alpha为0 或移除原来的
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIRefreshControl *)refresh
{
    if (!_refresh)
    {
        _refresh = [[UIRefreshControl alloc]init];
//        [self.tableView addSubview:_refresh];
    }
    return _refresh;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化页面
    [self showLoadingView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.leftButton.hidden = YES;
    self.titleLabel.text = @"本地生活圈";
    
    // 定位  成功获取身边数据 否则默认经纬度获取数据
    [LRLocationManager getLocationSuccess:^(CLLocation *location) {
        self.location = location.coordinate;
        // 连接网络获取数据
        [self getData];
    } fail:^(NSError *error) {
//        [MBProgressHUD showError:error.domain];
        // 设置默认值
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(36.06, 120.38);
        self.location = coord;
        // 连接网络获取数据
        [self getData];
    }];
    
    // 设置tableview的头部
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.header = [[[NSBundle mainBundle]loadNibNamed:@"LRHomeHeardCell" owner:nil options:nil] lastObject];
    
    self.header.frame = CGRectMake(0, 0, kUIScreenW, 170);

    self.tableView.tableHeaderView = self.header;
    
}

- (void)getData
{
    NSString *homeStr = @"http://www.qd-life.com/?anu=api/1/index/get_index_info";
    
    // 参数设置
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[NSString stringWithFormat:@"%f",self.location.longitude] forKey:@"lon"];
    [params setObject:[NSString stringWithFormat:@"%f",self.location.latitude] forKey:@"lat"];
    [params setObject:[LRFunction getTimeScamp] forKey:@"time"];
    NSArray *arr = @[APP_ID,params[@"lon"],params[@"lat"],params[@"time"],APP_IDENGER];
    [params setObject:[LRFunction md5StringFromArray:arr] forKey:@"sign"];
    [params setObject:APP_IDENGER forKey:@"app_id"];
    
    [self.manager GET:homeStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *resultStatus = responseObject[@"status"];
        if ([resultStatus isEqualToString:@"error"])
        {
            [MBProgressHUD showError:@"请求失败，请稍后再试！"];
            return ;
        }
        // 设置模型数据
        self.homeModel = [[LRHomeModel alloc]initWithDictionary:responseObject error:nil];
        
        self.header.focus = self.homeModel.focus;
        
        [self.tableView reloadData];
        [self hidenLoadingView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:@"网络请求失败,请稍后再试...."];
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    LRLog(@"LRHomeControll-dealloc");
}

#pragma mark - UITableView 数据源和代理方法实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else if (section == 1)
        return 1;
    else
        return self.homeModel.guess.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0)
    {
        static NSString *groupId = @"LRGroupTableViewCell";
        LRGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:groupId];
        if (!cell)
        {
            cell = [[[UINib nibWithNibName:groupId bundle:nil]instantiateWithOwner:self options:nil]lastObject];
        }
        cell.group = self.homeModel.group;
        
        return cell;
    }
    else if (indexPath.section == 1)
    {
        static NSString *famousId = @"LRFamousTableViewCell";
        LRFamousTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:famousId];
        
        if (!cell)
        {
            cell = [[[NSBundle mainBundle]loadNibNamed:famousId owner:self options:nil]lastObject];
        }
        cell.delegate = self;
        cell.famous = self.homeModel.famous;

        return cell;
    }
    else if (indexPath.section == 2)
    {
        static NSString *guessId = @"LRGuessTableViewCell";
        LRGuessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:guessId];
        if (!cell)
        {
            cell = [[[NSBundle mainBundle]loadNibNamed:guessId owner:self options:nil]lastObject];
        }
        cell.list = self.homeModel.guess.list[indexPath.row];
        return cell;
    }
    return nil;
}
#define kUITableViewSectionHeaderHeight 40
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenW, kUITableViewSectionHeaderHeight)];
    view.backgroundColor = [UIColor whiteColor];
    
    //添加上分割线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUIScreenW, 5)];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 6, kUIScreenW - 10, kUITableViewSectionHeaderHeight - 6)];
    if (section == 1)
        titleLabel.text = @"名店推荐";
    else if (section == 2)
        titleLabel.text = @"猜你喜欢";
    titleLabel.font = [UIFont fontWithName:@"Menlo" size:20];
    [titleLabel setTextColor:[UIColor redColor]];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:titleLabel];
    
    //添加下上分割线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, kUITableViewSectionHeaderHeight - 1, kUIScreenW, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
     if (section == 1 || section == 2)
    {
        return kUITableViewSectionHeaderHeight;
    }
    else
        return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 )
    {
        return 177;
    }
    else if (indexPath.section == 1)
        return 180;
    else
        return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2)
    {
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"小二,%@来一份",[self.homeModel.guess.list[indexPath.row] title]]];
    }
}

#pragma mark - LRFamousListDelegate
- (void)didGotoDetailWithfamouslist:(LRFamousListModel *)famous
{
    // 获取数据
    NSString *detailStr = @"http://www.qd-life.com/api/1/shop/get_shop_info";
    
    // 参数设置
    NSString *Id = [NSString stringWithFormat:@"%d",famous.id]; // 待验证
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:Id forKey:@"shop_id"];
    [params setObject:[LRFunction getTimeScamp] forKey:@"time"];
    NSArray *arr = @[APP_ID,params[@"shop_id"],params[@"time"],APP_IDENGER];
    [params setObject:[LRFunction md5StringFromArray:arr] forKey:@"sign"];
    [params setObject:APP_ID forKey:@"app_id"];
    
    [self.manager POST:detailStr parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id result = responseObject[@"status"];
        if ([result isEqualToString:@"error"])
        {
            [MBProgressHUD showError:@"请求失败,请稍后再试"];
        }
        // 解析数据模型
        LRDetailFamousModel *detail = [[LRDetailFamousModel alloc]initWithDictionary:responseObject error:nil];

        CGRect rect = [detail.intro boundingRectWithSize:CGSizeMake(kUIScreenW, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:14]} context:nil];
        LRDetailFamousViewController *detailVc = [[LRDetailFamousViewController alloc]init];
        detailVc.detail = detail;

        detailVc.heightForHeader = 160 + rect.size.height;
        
        [self.navigationController pushViewController:detailVc animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:@"网络无法访问,请检查网络"];
    }];

}
@end
